package org.greyhawk.logger;

import java.util.HashMap;
import java.util.Map;

/**
 * Created at 10:57 PM on 8/20/12
 *
 * @author Russ Jackson (last updated by $Author$)
 * @version $Revision$, $Date$
 */
public class LoggerFactory {

    // requests for the same logger should return the same Logger instance
    private static final Map<org.slf4j.Logger, Logger> _loggerMap
        = new HashMap<org.slf4j.Logger, Logger>();

    // there is a 1-1 mapping between slf4j logger instances and the slf4j5 wrapper
    // loggers
    private static Logger getMappedLogger(org.slf4j.Logger wrappedLogger) {
        Logger result = _loggerMap.get(wrappedLogger);
        if (null == result) {
            result = new Logger(wrappedLogger);
            _loggerMap.put(wrappedLogger, result);
        }
        return result;
    } // getMappedLogger()

    /**
     * Get a Logger instance for the given class; the slf4j LoggerFactory is used
     * internally to get the appropriate implementation
     *
     * @param aClass class reference
     * @return Logger instance which wraps an slf4j Logger implementation
     */
    public static Logger getLogger(Class aClass) {
        org.slf4j.Logger wrappedLogger = org.slf4j.LoggerFactory.getLogger(aClass);
        return getMappedLogger(wrappedLogger);
    } // getLogger()

    /**
     * get a Logger without supplying a name or a class
     *
     * @return a Logger for the class calling this method, if that class exists,
     * otherwise, a Logger with the calling class name; the returned logger is
     * a wrapper around an slf4j Logger implementation
     */
    public static Logger getLogger() {
        Logger result = null;

        String callingClass = Thread.currentThread().getStackTrace()[2].getClassName();
        try {
            result = getLogger(Class.forName(callingClass));
        } catch (ClassNotFoundException e) {
            result = getLogger(callingClass);
        }

        return result;
    } // getLogger()

    /**
     * get the Logger mapped to the given name
     *
     * @param name name of the Logger to fetch
     * @return the Logger instance associated with the given name;  the Logger
     * instance wraps an slf4j Logger implementation
     */
    public static Logger getLogger(String name) {
        org.slf4j.Logger wrappedLogger = org.slf4j.LoggerFactory.getLogger(name);
        return getMappedLogger(wrappedLogger);
    } // getLogger()

} // class LoggerFactory
